#include "serverHead/transFile.h"

int transFile(int netfd,char* filename){
    int fd=open(filename,O_RDWR);
    if(fd==-1){
        return fd;
    }
    train_t train;
    struct stat stat_file;
    fstat(fd,&stat_file);
    //send file size
    train.order=ORDER_ERROR;
    train.dataLen=sizeof(stat_file.st_size);
    memcpy(train.data,&stat_file.st_size,train.dataLen);
    send(netfd,&train,sizeof(TokenType_)+sizeof(int)+train.dataLen,MSG_NOSIGNAL);
    if(stat_file.st_size<FILE_MAX_SIZE){
        char* p=(char*)mmap(NULL,stat_file.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
        if(p==MAP_FAILED){
            return -1;
        }
        off_t totalsize=0;
        while(totalsize<stat_file.st_size){
            if(stat_file.st_size-totalsize<4096){
                train.dataLen=stat_file.st_size-totalsize;
            }else{
                train.dataLen=4096;
            }
            send(netfd,&train.dataLen,sizeof(train.dataLen),MSG_NOSIGNAL);
            send(netfd,p+totalsize,train.dataLen,MSG_NOSIGNAL);
            totalsize+=train.dataLen;
        }
        //space train
        train.dataLen=0;
        send(netfd,&train.dataLen,sizeof(train.dataLen),MSG_NOSIGNAL);
        munmap(p,stat_file.st_size);
        close(fd);
        return 0;
    }
    sendfile(netfd,fd,NULL,stat_file.st_size);
    close(fd);
    return 0;
}


